package window.panel;

import entity.OrderInfo;
import manage.OrderDBManager;
import manage.UsernameController;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class OrderPanel extends JPanel {
    private ArrayList<OrderInfo> orderlist = OrderDBManager.getOrders(UsernameController.getUsername());
    private DefaultTableModel model;

    public OrderPanel() {
        setLayout(new BorderLayout());

        // Create table model with column names
        model = new DefaultTableModel();
        String[] columnData1 = {"Order ID", "Order Name", "Product Type", "Number", "Price", "Action"};
        model.setColumnIdentifiers(columnData1);

        // Create table with custom cell renderer and editor for buttons
        JTable table = new JTable(model) {
            @Override
            public Class<?> getColumnClass(int column) {
                return (column == 5) ? JButton.class : Object.class;
            }
        };

        table.setRowHeight(30);

        // Set custom renderer and editor for the button column
        table.getColumnModel().getColumn(5).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(5).setCellEditor(new ButtonEditor(new JCheckBox(), table));

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Table with Buttons");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(600, 400);
            frame.add(new OrderPanel());
            frame.setVisible(true);
        });
    }

    public void loadOrders() {
        // Remove all rows before adding new data
        model.setRowCount(0);

        orderlist = OrderDBManager.getOrders(UsernameController.getUsername());
        System.out.println(orderlist);
        int i = 0;
        for (OrderInfo orderInfo : orderlist) {
            model.addRow(new Object[]{orderInfo.getId(), orderInfo.getOrderName(), orderInfo.getOrderType(), orderInfo.getNumber(), orderInfo.getPrice(), "Cancel"});
            i++;
        }
        revalidate();
        repaint();
    }

    // Custom renderer for the button
    static class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setText("Cancel");
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            return this;
        }
    }

    // Custom editor for the button
    class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private OrderInfo targetOrder;
        private boolean isPushed;
        private JTable table;

        public ButtonEditor(JCheckBox checkBox, JTable table) {
            super(checkBox);
            this.table = table;
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fireEditingStopped();
                    int response = JOptionPane.showConfirmDialog(button, "Are you sure you want to cancel this order?", "Confirm Cancel", JOptionPane.YES_NO_OPTION);
                    if (response == JOptionPane.YES_OPTION) {
                        OrderDBManager.cancelOrder(targetOrder);
                        loadOrders();
                    }
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            int targetOrderId = (int) table.getValueAt(row, 0); // Set orderId as a property of the button
            for (OrderInfo order : orderlist) {
                if (order.getId() == targetOrderId) {
                    targetOrder = order;
                    break;
                }
            }
            button.setText((value == null) ? "" : value.toString());
            isPushed = true;
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            isPushed = false;
            return button.getText();
        }

        @Override
        public boolean stopCellEditing() {
            isPushed = false;
            return super.stopCellEditing();
        }

        @Override
        protected void fireEditingStopped() {
            super.fireEditingStopped();
        }
    }
}
